package me.zhengjie.modules.deviceposition.service.impl;

import me.zhengjie.modules.deviceposition.domain.DevicePosition;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.deviceposition.repository.DevicePositionRepository;
import me.zhengjie.modules.deviceposition.service.DevicePositionService;
import me.zhengjie.modules.deviceposition.service.dto.DevicePositionDTO;
import me.zhengjie.modules.deviceposition.service.mapper.DevicePositionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 张鹏
 * @date 2019-06-05
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DevicePositionServiceImpl implements DevicePositionService {

    @Autowired
    private DevicePositionRepository devicePositionRepository;

    @Autowired
    private DevicePositionMapper devicePositionMapper;

    @Override
    public DevicePositionDTO findById(Long id) {
        Optional<DevicePosition> devicePosition = devicePositionRepository.findById(id);
        ValidationUtil.isNull(devicePosition, "DevicePosition", "id", id);
        return devicePositionMapper.toDto(devicePosition.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DevicePositionDTO create(DevicePosition resources) {
        return devicePositionMapper.toDto(devicePositionRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DevicePosition resources) {
        Optional<DevicePosition> optionalDevicePosition = devicePositionRepository.findById(resources.getId());
        ValidationUtil.isNull(optionalDevicePosition, "DevicePosition", "id", resources.getId());

        DevicePosition devicePosition = optionalDevicePosition.get();
        // 此处需自己修改
        resources.setId(devicePosition.getId());
        devicePositionRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        devicePositionRepository.deleteById(id);
    }

    public List<Map<String, String>> deviceDict() {
        return devicePositionRepository.deviceDict();
    }
}